//
//  Test3Controller.swift
//  STest
//
//  Created by wang tiao on 2025/9/13.
//

import UIKit
import Lottie

class Test3Controller: UIViewController, ExpandableLabelDelegate {
    private var animationView: LottieAnimationView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        //        // 初始化动画
        //        animationView = LottieAnimationView(name: "cr1")
        //        animationView.frame = CGRect(x: 50, y: 100, width: 200, height: 200)
        //        animationView.contentMode = .scaleAspectFit
        //        animationView.loopMode = .loop // 循环播放
        //
        //        view.addSubview(animationView)
        //
        //        // 播放
        //        animationView.play()
        //
        //
        //        let spinner = GradientDotSpinnerView(frame: CGRect(x: 100, y: 300, width: 50, height: 50))
        //        spinner.dotCount = 12
        //        spinner.radius = 25
        //        spinner.dotSize = 10
        //        spinner.gradientColors = [.red, .orange, .yellow, .green, .blue, .purple]
        //        view.addSubview(spinner)
        //        spinner.startAnimating()
        //
        //
        
//        let label = ExpandableLabel()
//        label.frame = CGRect(x: 20, y: 100, width: 200, height: 200)
//        label.font = .systemFont(ofSize: 14)
//        label.numberOfLines = 0
//        label.setText("这是一个很长很长很长很长的文本需要截断是一个很长很长很长很长的文本需要截断显示是一个很长很长很长很长的文本需要截断显示是一个很长很长很长很长的文本需要截断显示是一个很长很长很长很长的文本需要截断显示显示", maxLines: 2)
//        view.addSubview(label)
//        
        
        let expandableLabel = ExpandableLabel()
        expandableLabel.font = .systemFont(ofSize: 16)
        expandableLabel.textColor = .darkText
        expandableLabel.delegate = self
        expandableLabel.numberOfLines = 0
        expandableLabel.setText("这是一个很长本需要截断是一个很长很长很长很长的文本需要本需要截断是一个很长很长很长很长的文本需要很长的文字，超出后会显示展开按钮...", maxLines: 2)
        
        view.addSubview(expandableLabel)
        expandableLabel.frame = CGRect(x: 20, y: 100, width: 300, height: 0)
        expandableLabel.sizeToFit()
        
    }
    
    
    func expandableLabelDidTapExpand(_ label: ExpandableLabel) {
        print("👉 点击了展开")
    }
}


protocol ExpandableLabelDelegate: AnyObject {
    func expandableLabelDidTapExpand(_ label: ExpandableLabel)
}

class ExpandableLabel: UILabel {
    var fullText: String = ""
    var maxLines: Int = 1
    weak var delegate: ExpandableLabelDelegate?
    
    private var isTruncated = false

    func setText(_ text: String, maxLines: Int = 1) {
        self.fullText = text
        self.maxLines = maxLines
        updateText()
        isUserInteractionEnabled = true
        addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap(_:))))
    }
    
    private func updateText() {
        guard let font = self.font else { return }
        
        let maxSize = CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude)
        let attributes: [NSAttributedString.Key: Any] = [.font: font]
        
        let text = fullText as NSString
        let bounding = text.boundingRect(with: maxSize,
                                         options: .usesLineFragmentOrigin,
                                         attributes: attributes,
                                         context: nil)
        
        let lineHeight = font.lineHeight
        let maxHeight = CGFloat(maxLines) * lineHeight
        
        if bounding.height > maxHeight {
            var truncated = fullText
            while truncated.count > 0 {
                truncated.removeLast()
                let test = truncated + "...展开"
                let testRect = (test as NSString).boundingRect(with: maxSize,
                                                               options: .usesLineFragmentOrigin,
                                                               attributes: attributes,
                                                               context: nil)
                if testRect.height <= maxHeight {
                    // 构造富文本
                    let attrString = NSMutableAttributedString(string: truncated + "...", attributes: [
                        .font: font,
                        .foregroundColor: self.textColor ?? .black
                    ])
                    
                    // “展开”样式：蓝色 + 下划线
                    let expandAttr = NSAttributedString(string: "展开", attributes: [
                        .font: font,
                        .foregroundColor: UIColor.systemBlue,
                        .underlineStyle: NSUnderlineStyle.single.rawValue
                    ])
                    
                    attrString.append(expandAttr)
                    self.attributedText = attrString
                    isTruncated = true
                    return
                }
            }
        } else {
            self.attributedText = NSAttributedString(string: fullText, attributes: [
                .font: font,
                .foregroundColor: self.textColor ?? .black
            ])
            isTruncated = false
        }
    }
    
    @objc private func handleTap(_ gesture: UITapGestureRecognizer) {
        guard isTruncated else { return }
        guard let text = attributedText else { return }
        
        let tapLocation = gesture.location(in: self)
        
        // 构造 textKit 组件
        let textStorage = NSTextStorage(attributedString: text)
        let layoutManager = NSLayoutManager()
        let textContainer = NSTextContainer(size: bounds.size)
        textContainer.lineFragmentPadding = 0
        textContainer.maximumNumberOfLines = maxLines
        textContainer.lineBreakMode = lineBreakMode
        
        layoutManager.addTextContainer(textContainer)
        textStorage.addLayoutManager(layoutManager)
        
        // 获取“展开”的 range
        let expandRange = NSRange(location: text.length - 2, length: 2)
        
        // 转换字符范围 → rect
        var glyphRange = NSRange()
        layoutManager.characterRange(forGlyphRange: expandRange, actualGlyphRange: &glyphRange)
        let expandRect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer)
        
        // ⚠️ 修正 Y 偏移（textContainer 和 UILabel 的坐标差异）
        let usedRect = layoutManager.usedRect(for: textContainer)
        let offsetY = (bounds.height - usedRect.height) / 2.0
        let correctedExpandRect = expandRect.offsetBy(dx: 0, dy: offsetY)
        
        // 判断点击是否命中
        if correctedExpandRect.contains(tapLocation) {
            delegate?.expandableLabelDidTapExpand(self)
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        updateText()
    }
}
